<script setup lang="ts">
import { useQueryFetch } from "@/nexus/useFetch";
import { formatDateFromString, formatPathToKey, formatter } from "@/utils/formatterUtils";

const props = defineProps({
  pageApi: {
    type: Object,
    required: true,
  },
  component: Object, // 传递组件
});
const route = useRoute();
const dialogRef = ref();
const removeIds = ref<number[]>([]);
const queryFormRef = ref();
const filters = ref<any>({});
const pageRequest = ref<any>({
  pageNum: 1,
  pageSize: 10,
});

const { data, loading } = useQueryFetch(props.pageApi.getPage, pageRequest);
const tableData = computed(() => data?.value?.list);
const total = computed(() => data?.value?.total);
// 获取权限的列表
const perm = computed(() => formatPathToKey(route.fullPath));

function toSearch() {
  pageRequest.value = {
    pageNum: 1,
    pageSize: 10,
    ...filters.value,
  };
}

/** 重置分类查询 */
function toReset() {
  queryFormRef.value.resetFields();
  filters.value = {};
  pageRequest.value = {
    pageNum: 1,
    pageSize: 10,
    ...filters.value,
  };
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 删除分类 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      props.pageApi
        .deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          toReset();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

defineExpose({
  loading,
  toReset,
});
</script>

<template>
  <div v-loading="loading" class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="filters" :inline="true">
        <slot name="formContent" :filters="filters"></slot>
        <el-form-item>
          <el-button v-hasPerm="[`${perm}:query`]" type="primary" @click="toSearch">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="toReset">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-[10px]">
        <el-button v-hasPerm="[`${perm}:add`]" type="success" icon="plus" @click="dialogRef.open()">
          新增
        </el-button>
        <el-button
          v-hasPerm="[`${perm}:delete`]"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" :formatter="formatter" />
        <slot name="tableContent" :tableData="tableData" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
          :formatter="formatDateFromString"
        ></el-table-column>
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
          :formatter="formatDateFromString"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="[`${perm}:edit`]"
              type="primary"
              size="small"
              link
              @click="dialogRef.open(scope.row)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="[`${perm}:delete`]"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="(total ?? 0) > 0"
        v-model:total="total"
        v-model:page="pageRequest.pageNum"
        v-model:limit="pageRequest.pageSize"
      />
    </el-card>
    <component :is="component" ref="dialogRef" :dialog-api="pageApi" @update-page-data="toReset" />
  </div>
</template>

<style scoped lang="scss"></style>
